<template>
  <div id="pieChart" style="width: 600px;height:400px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';

export default {
  name: 'PieChartComponent',
  data() {
    return {
      chartData: [],
      billTypes: [],
    };
  },
  computed: {
    // Computed property to aggregate data for the pie chart
    pieChartData() {
      const categorizedData = {};
      // Create a map from billTypes to quickly find names by typeId
      const typeNames = this.billTypes.reduce((acc, type) => {
        acc[type.typeId] = type.name;
        return acc;
      }, {});

      this.chartData.forEach(item => {
        const typeName = typeNames[item.typeId];
        if (typeName) {
          if (!categorizedData[typeName]) {
            categorizedData[typeName] = {
              name: typeName,
              value: 0,
            };
          }
          categorizedData[typeName].value += item.money;
        }
      });

      return Object.values(categorizedData);
    },
  },
  mounted() {
    this.loadAll()
        .then(() => {
          this.initChart();
        })
        .catch(error => {
          console.error('Error loading data:', error);
        });
  },
  methods: {
    initChart() {
      const myChart = echarts.init(document.getElementById('pieChart'));
      const option = {
        title: {
          text: '消费分类',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
          {
            name: '消费',
            type: 'pie',
            radius: '55%',
            center: ['50%', '50%'],
            data: this.pieChartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      myChart.setOption(option);
    },
    async loadAll() {
      try {
        const [billInfoResponse, billTypeResponse] = await Promise.all([
          axios.get('https://youxuan-zua-api.tulan.wang/admin/ysf-bill-info/findPage?page=1&size=20'),
          axios.get('https://youxuan-zua-api.tulan.wang/admin/ysf-bill-type/page')
        ]);

        this.chartData = billInfoResponse.data.data; // Assuming data is under the 'data' key
        this.billTypes = billTypeResponse.data.data; // Assuming data is under the 'data' key
      } catch (error) {
        throw new Error('Failed to load data.');
      }
    },
  }
};
</script>